<template>
  <div v-enter-helper="getList" class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate"
          >&emsp;新增&emsp;
          </el-button
          >
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          style="width:100%;margin-bottom: 20px;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="序号" prop="id" width="70"></el-table-column>
          <el-table-column label="礼包名称" prop="name"></el-table-column>
          <el-table-column label="礼包内容" prop="gift_bag_detail">
            <template slot-scope="scope">
              <div style="display:flex;flex-direction:column;">
                <div
                  v-for="(item, index) in scope.row.gift_bag_detail"
                  :key="index"
                  style="margin:5px;"
                >
                  <el-tag v-if="item.type === 1" type="warning"
                  >金币x{{ item.gold }}个
                  </el-tag
                  >
                  <el-tag v-if="item.type === 2" type="success"
                  >{{ item.name }}x{{ item.quantity }}个
                  </el-tag
                  >
                  <el-tag v-if="item.type === 3" type="danger"
                  >{{ item.name }}x{{ item.days }}天
                  </el-tag
                  >
                  <el-tag v-if="item.type === 4" type="primary"
                  >{{ item.name }}x{{ item.days }}天
                  </el-tag
                  >
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="添加时间" prop="add_time"></el-table-column>
          <el-table-column label="状态" prop="status" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
              <el-tag v-if="scope.row.status === 0" type="danger"
              >未启用
              </el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-present"
                plain
                size="mini"
                type="warning"
                @click="handleGive(scope.row)"
              >赠送
              </el-button>
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style:normal;color:red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose('editRulesForm')"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="80px"
      >
        <el-form-item label="礼包名称" prop="name">
          <el-input
            v-model="editRulesForm.name"
            clearable
            placeholder="请输入礼包名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="金币" prop="gold">
          <el-input
            v-model.number="editRulesForm.gold"
            clearable
            placeholder="请输入金币数量"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in editRulesForm.giftArr"
          :key="'礼物' + index"
          label="礼物"
        >
          <el-select
            v-model="item.foreign_id"
            filterable
            placeholder="请选择礼物"
            style="margin-bottom:20px"
          >
            <el-option
              v-for="item in giftType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.quantity"
            placeholder="请输入礼物数量"
            style="margin-bottom:20px; width:200px"
          ></el-input>
          <el-button @click.prevent="removeGift(item)">删除</el-button>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in editRulesForm.mountArr"
          :key="'坐骑' + index"
          label="坐骑"
        >
          <el-select
            v-model="item.foreign_id"
            filterable
            placeholder="请选择坐骑"
            style="margin-bottom:20px"
            @change="handleForeign"
          >
            <el-option
              v-for="item in mountType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.days"
            disabled
            placeholder="请输入坐骑天数"
            style="margin-bottom:20px; width:200px"
          ></el-input>
          <el-button @click.prevent="removeMount(item)">删除</el-button>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in editRulesForm.pendantArr"
          :key="'挂件' + index"
          label="挂件"
        >
          <el-select
            v-model="item.foreign_id"
            filterable
            placeholder="请选择挂件"
            style="margin-bottom:20px"
            @change="handleRide"
          >
            <el-option
              v-for="item in pendantType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.days"
            disabled
            placeholder="请输入挂件天数"
            style="margin-bottom:20px; width:200px"
          ></el-input>
          <el-button @click.prevent="removePendant(item)">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addGift">新增礼物</el-button>
          <el-button type="primary" @click="addMount">新增坐骑</el-button>
          <el-button type="primary" @click="addPendant">新增挂件</el-button>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
            <el-input  v-model="editRulesForm.sort" clearable placeholder="请输入排序数字"></el-input>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editRulesForm.status">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
          >提交
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 赠送弹框 -->
    <el-dialog
      v-dialogDrag
      :visible.sync="giveFormVisible"
      title="赠送"
      @close="handleDialogClose('giveForm')"
    >
      <el-form
        ref="giveForm"
        :model="giveForm"
        :rules="giveFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="礼包名称">
          <el-input
            v-model="giveForm.name"
            disabled
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="金币">
          <el-input v-model="giveForm.gold" disabled type="number"></el-input>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in giveForm.giftArr"
          :key="'礼物' + index"
          label="礼物"
        >
          <el-select
            v-model="item.foreign_id"
            disabled
            filterable
            placeholder="请选择礼物"
            style="margin-bottom:20px"
          >
            <el-option
              v-for="item in giftType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.quantity"
            disabled
            placeholder="请输入礼物数量"
            style="margin-bottom:20px"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in giveForm.mountArr"
          :key="'坐骑' + index"
          label="坐骑"
        >
          <el-select
            v-model="item.foreign_id"
            disabled
            filterable
            placeholder="请选择坐骑"
            style="margin-bottom:20px"
          >
            <el-option
              v-for="item in mountType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.days"
            disabled
            placeholder="请输入坐骑天数"
            style="margin-bottom:20px"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in giveForm.pendantArr"
          :key="'挂件' + index"
          label="挂件"
        >
          <el-select
            v-model="item.foreign_id"
            disabled
            filterable
            placeholder="请选择挂件"
            style="margin-bottom:20px"
          >
            <el-option
              v-for="item in pendantType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model.number="item.days"
            disabled
            placeholder="请输入挂件天数"
            style="margin-bottom:20px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户编号" prop="user_code">
          <el-input v-model="giveForm.user_code" type="text"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="giveFormVisible = false">返回</el-button>
          <el-button type="primary" @click="giveSubmit('giveForm')"
          >提交
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  listTypeData,
  postAddData,
  putEditData,
  deleteData,
  postGiveData
} from "@/api/member/memberBag";
import { getToken } from "@/utils/auth";

;

export default {
  data() {
    return {
      confirmBtn: false,
      giveShowPicture: [],
      giveFormRules: {
        user_code: [
          { required: true, message: "请输入用户编号", trigger: "blur" }
        ]
      },
      giveForm: {
        name: undefined,
        gold: undefined,
        user_code: undefined,
        giftArr: [],
        mountArr: [],
        pendantArr: []
      },
      giveFormVisible: false,

      // 徽章状态
      badgeStatus: [
        { value: 1, label: "开启" },
        { value: 2, label: "隐藏" }
      ],
      // 要修改的当前行的idsearchSubmit
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        name: [
          {
            required: true,
            message: "请输入名称1-30字符",
            trigger: "blur",
            min: 1,
            max: 30
          }
        ],
        sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }]
      },
      giftType: [],
      mountType: [],
      pendantType: [],
      editRulesForm: {
        name: undefined,
        gold: undefined,
        // sort:undefined,
        status: 1,
        giftArr: [],
        mountArr: [],
        pendantArr: []
      },
      dialogStatus: "",
      // dialog的头部信息
      titleMap: {
        update: "编辑",
        create: "新增"
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ""
    };
  },
  created() {
    this.getTypeList();
    this.getList();
  },
  methods: {
    handleRelease(row) {
      this.row_id = row.id;
      putRelease(this.row_id).then(response => {
        if (response.code === 200) {
          this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: "error"
          });
        }
      });
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      listData(urlData).then(response => {
        this.menuList = response.data.list;
        this.total = response.data.meta.total;
        this.listLoading = false;
        this.confirmBtn = false;
      });
    },
    getTypeList() {
      listTypeData().then(response => {
        response.data.gift.forEach(item => {
          this.giftType.push({ value: item.id, label: item.name });
        });
        response.data.ride.forEach(item => {
          this.mountType.push({
            value: item.id,
            label: item.title,
            day: item.day
          });
        });
        response.data.head.forEach(item => {
          this.pendantType.push({
            value: item.id,
            label: item.title,
            day: item.day
          });
        });
      });
    },
    searchSubmit() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetSubmit() {
      this.listQuery.page = 1;
      this.listQuery.perPage = 10;
      this.listQuery.type_id = undefined;
      this.listQuery.status = undefined;
      this.listQuery.keyword = undefined;
    },
    // 点击新增
    handleCreate() {
      this.resetForm("editRulesForm");
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    addGift() {
      this.editRulesForm.giftArr.push({
        foreign_id: "",
        type: 2,
        quantity: ""
      });
    },
    addMount() {
      this.editRulesForm.mountArr.push({
        foreign_id: "",
        type: 3,
        days: ""
      });
    },
    addPendant() {
      this.editRulesForm.pendantArr.push({
        foreign_id: "",
        type: 4,
        days: ""
      });
    },
    removeGift(item) {
      let index = this.editRulesForm.giftArr.indexOf(item);
      if (index !== -1) {
        this.editRulesForm.giftArr.splice(index, 1);
      }
    },
    removeMount(item) {
      let index = this.editRulesForm.mountArr.indexOf(item);
      if (index !== -1) {
        this.editRulesForm.mountArr.splice(index, 1);
      }
    },
    removePendant(item) {
      let index = this.editRulesForm.pendantArr.indexOf(item);
      if (index !== -1) {
        this.editRulesForm.pendantArr.splice(index, 1);
      }
    },
    handleForeign(item) {
      // 遍历礼物列表 找到选择的礼物id对应的天数
      this.mountType.forEach(i => {
        if (i.value === item) {
          // 遍历
          this.editRulesForm.mountArr.forEach(x => {
            if (x.foreign_id === item) {
              x.days = i.day;
            }
          });
        }
      });
    },
    handleRide(item) {
      // 遍历礼物列表 找到选择的礼物id对应的天数
      this.pendantType.forEach(i => {
        if (i.value === item) {
          // 遍历
          this.editRulesForm.pendantArr.forEach(x => {
            if (x.foreign_id === item) {
              x.days = i.day;
            }
          });
        }
      });
    },

    // 点击编辑
    handleUpdate(row) {
      this.editRulesForm.giftArr = [];
      this.editRulesForm.mountArr = [];
      this.editRulesForm.pendantArr = [];
      this.row_id = row.id;
      this.editRulesForm.name = row.name;
      this.editRulesForm.status = row.status;
      row.gift_bag_detail.forEach(item => {
        if (item.type === 1) {
          this.editRulesForm.gold = item.gold;
        } else if (item.type === 2) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.quantity = item.quantity;
          this.editRulesForm.giftArr.push(obj);
        } else if (item.type === 3) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.days = item.days;
          this.editRulesForm.mountArr.push(item);
        } else if (item.type === 4) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.days = item.days;
          this.editRulesForm.pendantArr.push(item);
        }
      });

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.cityList = [];
        this.editRulesForm = {
          name: undefined,
          gold: undefined,
          status: 1,
          giftArr: [],
          mountArr: [],
          pendantArr: []
          /*
          gift_type_id:undefined,
          mount_type_id:undefined,
          pendant_type_id:undefined,
          giftValue:undefined,
          mountValue:undefined,
          pendantValue:undefined, */
        };
      });
    },
    submitForm(formName) {
      if (this.confirmBtn) return;
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.confirmBtn = true;
          if (this.dialogStatus === "create") {
            let obj = {};
            obj["name"] = this.editRulesForm.name;
            obj["status"] = this.editRulesForm.status;
            obj["gift_bag_detail"] = [];
            let goldObj = {};
            if (this.editRulesForm.gold) {
              goldObj["gold"] = this.editRulesForm.gold;
              goldObj["type"] = 1;
              obj["gift_bag_detail"].push(goldObj);
            }
            if (this.editRulesForm.giftArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.giftArr)
              this.editRulesForm.giftArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            if (this.editRulesForm.mountArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.mountArr)
              this.editRulesForm.mountArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            if (this.editRulesForm.pendantArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.pendantArr)
              this.editRulesForm.pendantArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            obj.gift_bag_detail = JSON.stringify(obj.gift_bag_detail);

            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.confirmBtn = false;
              }
            });
          } else {
            let obj = {};
            obj["name"] = this.editRulesForm.name;
            obj["status"] = this.editRulesForm.status;
            obj["gift_bag_detail"] = [];
            let goldObj = {};
            if (this.editRulesForm.gold) {
              goldObj["gold"] = this.editRulesForm.gold;
              goldObj["type"] = 1;
              obj["gift_bag_detail"].push(goldObj);
            }
            if (this.editRulesForm.giftArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.giftArr)
              this.editRulesForm.giftArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            if (this.editRulesForm.mountArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.mountArr)
              this.editRulesForm.mountArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            if (this.editRulesForm.pendantArr.length !== 0) {
              // obj['gift_bag_detail'].concat(this.editRulesForm.pendantArr)
              this.editRulesForm.pendantArr.forEach(item => {
                obj["gift_bag_detail"].push(item);
              });
            }
            obj.gift_bag_detail = JSON.stringify(obj.gift_bag_detail);
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.confirmBtn = false;
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    handleGive(row) {
      this.giveForm.user_code = undefined;
      this.giveForm.giftArr = [];
      this.giveForm.mountArr = [];
      this.giveForm.pendantArr = [];
      this.row_id = row.id;
      this.giveForm.name = row.name;
      this.giveForm.status = row.status;
      row.gift_bag_detail.forEach(item => {
        if (item.type === 1) {
          this.giveForm.gold = item.gold;
        } else if (item.type === 2) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.quantity = item.quantity;
          this.giveForm.giftArr.push(obj);
        } else if (item.type === 3) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.days = item.days;
          this.giveForm.mountArr.push(item);
        } else if (item.type === 4) {
          let obj = {};
          obj.foreign_id = item.foreign_id;
          obj.type = item.type;
          obj.days = item.days;
          this.giveForm.pendantArr.push(item);
        }
      });
      this.giveFormVisible = true;
    },
    giveSubmit(formName) {
      if (this.confirmBtn) return;
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.confirmBtn = true;
          let obj = {};
          obj.user_codes = this.giveForm.user_code;
          postGiveData(this.row_id, obj).then(response => {
            if (response.code === 200) {
              // this.getList()
              this.giveFormVisible = false;
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000
              });
            } else {
              this.confirmBtn = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` };
      this.deleteDialogVisible = true;
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: "请先勾选要删除的内容",
          type: "warning"
        });
        return;
      } else if (this.multipleSelection.length !== 0) {
        let ids = "";
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`;
        }
        ids = ids.substring(0, ids.length - 1);
        this.dataIds = { ids: ids };
      }
      this.deleteDialogVisible = true;
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return;
      this.confirmBtn = true;
      this.deleteDialogVisible = false;
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList();
          this.deleteDialogVisible = false;
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          this.confirmBtn = false;
        }
      });
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate(); // 清除整个表单的校验
      }
    }
  }
};
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both;
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

.el-table .tagDiv {
  display : block;
}

/deep/ .el-table_1_column_4 .cell {
  display        : flex;
  flex-direction : column;
}

/deep/ .el-table_1_column_4 .cell > div {
  margin-bottom : 10px;
}

/* /deep/ .el-card__header {
    padding-bottom: 0;
} */

/* .avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
} */
</style>
